using System.Linq;
using System.Threading.Tasks;
using CRM.Extensions;
using CRM.Models;
using CRM.ViewModels.Email;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;

namespace CRM.Controllers.Email;

[Route("api/[controller]")]
[ApiController]
public class EmailBlackListController : BaseController
{
    private readonly MyDbContext _dbContext;
    private readonly UserManager<User> _userManager;

    public EmailBlackListController(MyDbContext dbContext, UserManager<User> userManager)
    {
        _dbContext = dbContext;
        _userManager = userManager;
    }
        
    [HttpDelete("{id:int}")]
    public async Task<ResultStruct> Delete(int id) 
    {
        var user = await _userManager.GetUserAsync(User);
        var row = await _dbContext.EmailBlackLists.Where(e =>
                e.OemId == user.OemId && e.CompanyId == user.CompanyId && e.GroupId == user.GroupId &&
                e.UserId == user.Id && e.Id == id)
            .FirstOrDefaultAsync();
        if (row == null) return Error(message: "无权操作");
        
        await _dbContext.EmailBlackLists.Where(m => m.Id == id).DeleteAsync();
        await _dbContext.SaveChangesAsync();
        return Success();
    }
        
        
    [HttpPost(nameof(Create))]
    public async Task<ResultStruct> Create(EmailBlackListCreateVM vm)
    {
        if (!ModelState.IsValid) return Error(message: ModelState.ToString());
        var user = await _userManager.GetUserAsync(User);
        
        var row = 
            await _dbContext.EmailBlackLists
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
                .Where(m => m.Email == vm.Email)
                .FirstOrDefaultAsync();
        if (row is not null)
            return Success(message: "黑名单已存在,跳过添加");
        
        var model = vm.NewModel(user);
        await _dbContext.EmailBlackLists.AddAsync(model);
        await _dbContext.SaveChangesAsync();
        return Success(new { Id = model.Id });
    }
        
    [HttpPost("[action]")]
    public async Task<ResultStruct> Edit(EmailBlackListCreateVM vm)
    {
        var user = await _userManager.GetUserAsync(User);
        var model = 
            await _dbContext.EmailBlackLists
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
                .Where(m => m.Id == vm.Id)
                .FirstAsync();
        vm.EditModel(model);
        await _dbContext.SaveChangesAsync();
        return Success(new { Id = vm.Id });
    }
}